package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserserviceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
        // 1.查询用户
        User user = getById(id);
        // 2.校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZE) {
            throw new RuntimeException("用户状态异常！");
        }
        // 3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        // 4.扣减余额 update tb_user set balance = balance - ?
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance) // 更新余额
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZE) // 动态判断，是否更新status
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .update();
    }

    @Override
    public UserVO queryUserAndAddressById(Long userId) {
        // 1.查询用户
        User user = getById(userId);
        if (user == null) {
            return null;
        }
        // 2.查询收货地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, userId)
                .list();
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 3.处理vo
        if(CollUtil.isNotEmpty(addresses)) {
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.查询用户
        List<User> users=listByIds(ids);
        if(CollUtil.isEmpty(users)) {
            return null;
        }
        //2.查询地址
        //2.1获取用户id集合
        List<Long> userIds=users.stream().map(User::getId).collect(Collectors.toList());
        //2.2根据用户id查询地址
        List<Address> addresses=Db.lambdaQuery(Address.class).in(Address::getUserId,userIds).list();
        //2.3转换地址vo
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4用户地址集合分组处理，相同用户的放入一个集合（组）中
        Map<Long,List<AddressVO>> addressMap=new HashMap<>();
        if(CollUtil.isNotEmpty(addressVOList)) {
            addressMap=addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        //3.转换成vo并返回
        List<UserVO> userVOList = new ArrayList<>(users.size());
        for(User user:users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressMap.get(user.getId()));
            userVOList.add(userVO);
        }
        return userVOList;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery query) {
        Page<User> page= query.toMpPageDefaultSortByUpdateTimeDesc();
        // 2.查询
        page(page);
        // 3.数据非空校验
        return PageDTO.of(page,user ->{
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            String username=user.getUsername();
            userVO.setUsername(username.substring(0,username.length()-2)+"**");
            return userVO;
        });
    }
}
